package com.example.mystoryapp2.ui.main.fragments

import android.annotation.SuppressLint
import android.widget.ArrayAdapter
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.mystoryapp2.R
import com.example.mystoryapp2.adapter.StoryListAdapter
import com.example.mystoryapp2.contexts.AppContext
import com.example.mystoryapp2.data.network.ServiceCreator
import com.example.mystoryapp2.data.network.model.StoryModel
import com.example.mystoryapp2.domain.Category
import com.example.mystoryapp2.domain.Story

class ReaderHomeViewModel : ViewModel() {
    var storyAdapter = MutableLiveData(StoryListAdapter(ArrayList()))
    private var categoryId = MutableLiveData<Int>()
    var name = MutableLiveData<String>()
    @SuppressLint("ResourceType")
    var adapter: ArrayAdapter<String> =
        ArrayAdapter(AppContext.application.baseContext, R.id.spCategory)

    val categoryStrList: List<String>
        get() = categoryList.map { it.getCategoryName() } // 假设Category类有一个name属性

    private var categoryList: ArrayList<Category> = StoryModel.categoryList

    init {
        adapter.addAll(categoryStrList)
        categoryList.add(StoryModel.getDefaultCategory())
        categoryId.value = -1
    }

    fun onItemSelected(position: Int) {
        categoryId.value = categoryList[position].getCategoryId()
    }

    fun search(){
        StoryModel.search(buildStory(),object: ServiceCreator.ICallBack<List<Story>>{
            override fun onSuccess(res: List<Story>) {
                storyAdapter.value?.setList(res as ArrayList<Story>)
            }
        })
    }

    private fun buildStory(): Story {
        val story = Story()
        story.setCategoryId(categoryId.value)
        story.setTitle(name.value)
        return story
    }

}